package cn.sccdlg.ssm.controller;

import cn.sccdlg.ssm.domain.Order;
import cn.sccdlg.ssm.service.OrderService;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

/**
 * @author RaoShuang
 * @emil 991207823@qq.com
 * @date 2020/10/28 21:03
 * 订单Controller
 */
@Controller
@RequestMapping("/order")
public class OrderController {
    private static final Logger logger = LoggerFactory.getLogger(OrderController.class);

    @Autowired
    private OrderService orderService;

    /** 错误页面*/
    private static final String ERROR_PAGE = "error";

    /**
     * 查询全部订单---未分页
     */
    @RequestMapping("/findAll/nonPaged.do")
    public ModelAndView findAll() {
        ModelAndView mv = new ModelAndView();
        try {
            List<Order> orderList = orderService.findAllNonPaged();
            mv.addObject("ordersList", orderList);
            mv.setViewName("orders-list");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("查询所有订单失败！未分页", e);
            mv.setViewName(ERROR_PAGE);
        }
        return mv;
    }

    /**
     * 查询全部订单---可分页
     * @param page 页码
     * @param size 每页条数
     * @throws Exception
     */
    @RequestMapping("/findAll.do")
    @Secured("ROLE_ADMIN")
    public ModelAndView findAll(@RequestParam(name = "page", required = true, defaultValue = "1") Integer page,
                                @RequestParam(name = "size", required = true, defaultValue = "4") Integer size) {
        ModelAndView mv = new ModelAndView();
        try {
            List<Order> ordersList = orderService.findAll(page, size);
            //PageInfo就是一个分页Bean
            PageInfo pageInfo = new PageInfo(ordersList);
            mv.addObject("pageInfo", pageInfo);
            mv.setViewName("orders-page-list");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("分页查询所有订单失败！", e);
            mv.setViewName(ERROR_PAGE);
        }
        return mv;
    }

    /**
     * 查询订单详情
     * @param ordersId 订单id
     * @throws Exception
     */
    @RequestMapping("/findById.do")
    public ModelAndView findById(@RequestParam(name = "id", required = true) String ordersId) throws Exception {
        ModelAndView mv = new ModelAndView();
        Order orders = orderService.findById(ordersId);
        mv.addObject("orders",orders);
        mv.setViewName("orders-show");
        return mv;
    }
}
